<template>
  <BasicModal v-bind="$attrs" @register="ztreeModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="ztreeForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  const formEdit: FormSchema[] = [
    {
      field: 'name',
      label: '目录名称',
      component: 'Input',
      required: true,
    },
  ];
  export default defineComponent({
    name: 'ZtreeModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],

    setup(_, { emit }) {
      const isUpdate = ref(true);

      const [ztreeForm, { setFieldsValue, validate }] = useForm({
        labelWidth: 100,
        schemas: formEdit,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      async function handleSubmit() {
        try {
          const values = await validate();
          console.log(values)
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const [ztreeModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        isUpdate.value = !!data?.isUpdate;
        if (!unref(isUpdate)) {
          setFieldsValue({
            name: '',
          });
        } else {
          setFieldsValue({
            ...data.graphApi,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增目录' : '编辑目录'));

      return {
        ztreeModal,
        getTitle,
        ztreeForm,
        handleSubmit,
      };
    },
  });
</script>
